package edpool;

public class DiffractingEliminationTree<T>
{
	final private Balancer<T> balancer;
	final private DiffractingEliminationTree<T>[] children;
	final int levelIndx;
	
    
    public DiffractingEliminationTree(int size, int levels)
    {
    	levelIndx = (int) Math.pow(2, levels - 1);
        balancer = new Balancer<T>(size, levels);
        if (size > 4 && levels > 1)
        {
            children = new DiffractingEliminationTree[]
                        {
            				new DiffractingEliminationTree<T>(size/4, levels -1),
            				new DiffractingEliminationTree<T>(size/4, levels -1)
                        };
         }
        else
        {
        	children = null;
        }
    }

     public int Traverse(ExchangerPackage<T> myPackage) 
     {
    	 balancer.traverseBalancer(myPackage);
    	 
    	 if (myPackage.getEliminationState() == EliminationStateEnum.Eliminated)
    		 return 0;
    	 
     	 int direction = myPackage.getDirection();
         
    	 if (children != null)
    	 {
    		return (children[direction].Traverse(myPackage) +  direction * levelIndx);
    	 }
        else
        	return direction;
         
    }

}
